package com.zziq.cloudpicturebank.job.cycle;

import com.zziq.cloudpicturebank.exception.ErrorCode;
import com.zziq.cloudpicturebank.exception.ThrowUtils;
import com.zziq.cloudpicturebank.model.entity.Space;
import com.zziq.cloudpicturebank.model.entity.User;
import com.zziq.cloudpicturebank.service.SpaceService;
import com.zziq.cloudpicturebank.service.UserService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Component
public class VipExpireTask {

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    /**
     * 每天凌晨零点零分零秒执行
     * 检查VIP过期用户，将VIP过期用户的角色改为普通用户，并将该用户创建的所有空间改为普通版
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void checkVipExpire() {
        System.out.println("开始检查VIP过期用户...");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        Date currentDate = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

        // 查询所有VIP过期的用户
        List<User> expiredUsers = userService.listExpiredVipUsers(currentDate);
        if (expiredUsers.isEmpty()){
            return;
        }
        // 开启事务1
        transactionTemplate.execute(status -> {
            for (User user : expiredUsers) {
                // 将用户角色改为 user
                user.setUserRole("user");
                boolean res = userService.updateById(user);
                ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR,"vip过期更新用户角色失败");

                // 查询该用户创建的所有空间
                List<Space> spaces = spaceService.listByUserId(user.getId());
                for (Space space : spaces) {
                    // 将空间级别改为普通版
                    space.setSpaceLevel(0);
                    boolean resSpace = spaceService.updateById(space);
                    ThrowUtils.throwIf(!resSpace, ErrorCode.OPERATION_ERROR,"vip过期更新空间级别失败");
                }
            }
            return true;
        });
        List<User> userList = userService.lambdaQuery().list();
        // 开启事务2
        transactionTemplate.execute(status -> {
            for (User user : userList) {
                switch (user.getUserRole()) {
                    case "user":
                        user.setDownloadCount(1);
                        break;
                    case "vip":
                        user.setDownloadCount(5);
                        break;
                    case "svip":
                        user.setDownloadCount(20);
                        break;
                    default:
                        user.setDownloadCount(999); // 默认值，可以根据需求调整
                        break;
                }
                boolean res = userService.updateById(user);
            }
            return true;
        });
    }
}